<!-- ArticleEditor.vue -->
<template>
    <div class="article-editor">
        <!-- 标题输入 -->
        <input v-model="formData.title" type="text" class="title-input" placeholder="请输入文章标题" maxlength="100">

        <!-- 标签管理 -->
        <!-- <div class="tags-section">
            <label>文章标签：</label>
            <div class="tags-container">
                <span v-for="(tag, index) in formData.tags" :key="index" class="tag">
                    {{ tag }}
                    <span class="remove-tag" @click="removeTag(index)">×</span>
                </span>
                <input v-model="newTag" type="text" class="tag-input" placeholder="输入标签后回车" @keyup.enter="addTag"
                    @keyup.delete="handleTagDelete">
            </div>
        </div> -->

        <!-- 富文本编辑器 -->
        <div class="editor-container">
            <QuillEditor v-model:content="formData.content" contentType="html" theme="snow" :options="editorOptions" />
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="error-message">⚠️ {{ error }}</div>

    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <el-button class="cancel-btn" :disabled="loading" @click="handleCancel">
            取消
        </el-button>
        <el-button class="save-btn" :disabled="loading" @click="handleSubmit">
            {{ loading ? '保存中...' : '保存文章' }}
        </el-button>
    </div>
</template>

<script setup>
import { ref, reactive, watchEffect, onMounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const props = defineProps({
    initialData: {
        type: Object,
        default: () => ({
            title: '',
            content: '',
            tags: []
        })
    },
    loading: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['save', 'cancel'])

// 表单数据
const formData = reactive({
    title: '',
    content: '',
    tags: []
})

// 标签管理
const newTag = ref('')

// 编辑器配置
const editorOptions = {
    modules: {
        toolbar: [
            [{ header: [1, 2, false] }],
            ['bold', 'italic', 'underline', 'blockquote'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link', 'image', 'video'],
            ['clean']
        ]
    }
}

// 错误提示
const error = ref('')

// 初始化数据
onMounted(() => {
    Object.assign(formData, props.initialData)
    loadDraft()
})

// 自动保存草稿
watchEffect(() => {
    const draft = {
        title: formData.title,
        content: formData.content,
        tags: formData.tags
    }
    localStorage.setItem('articleDraft', JSON.stringify(draft))
})

// 加载草稿
const loadDraft = () => {
    const draft = localStorage.getItem('articleDraft')
    if (draft) {
        try {
            const parsedDraft = JSON.parse(draft)
            Object.assign(formData, parsedDraft)
        } catch (e) {
            console.error('加载草稿失败:', e)
        }
    }
}

// 添加标签
const addTag = () => {
    if (newTag.value.trim() && formData.tags.length < 5) {
        formData.tags.push(newTag.value.trim())
        newTag.value = ''
    }
}

// 删除标签
const removeTag = (index) => {
    formData.tags.splice(index, 1)
}

// 处理标签删除键
const handleTagDelete = () => {
    if (newTag.value === '' && formData.tags.length > 0) {
        formData.tags.pop()
    }
}

// 表单验证
const validate = () => {
    if (!formData.title.trim()) {
        error.value = '标题不能为空'
        return false
    }
    if (!formData.content.trim()) {
        error.value = '内容不能为空'
        return false
    }
    error.value = ''
    return true
}

// 提交处理
const handleSubmit = () => {
    if (!validate()) return

    const articleData = {
        ...formData,
        updatedAt: new Date().toISOString()
    }

    emit('save', articleData)
}

// 取消处理
const handleCancel = () => {
    console.log('[ aaaa ] >', "aaaa")
    localStorage.removeItem('articleDraft')
    emit('cancel')
}
</script>

<style scoped>
.article-editor {
    max-width: 1200px;
    /* margin: 0 auto; */
    /* padding: 24px; */
}

.title-input {
    width: 100%;
    font-size: 1rem;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.tags-section {
    margin-bottom: 20px;
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.tag {
    background-color: #f0f2f5;
    padding: 4px 8px;
    border-radius: 4px;
    display: flex;
    align-items: center;
}

.remove-tag {
    cursor: pointer;
    margin-left: 4px;
    color: #999;
}

.tag-input {
    padding: 4px;
    border: 1px solid #ddd;
    border-radius: 4px;
    min-width: 120px;
}

.editor-container {
    height: 600px;
    width: 120%;
    margin-bottom: 20px;
}

.action-buttons {
    margin-top: 6%;
    margin-left: 60%;
    gap: 12px;
    justify-content: flex-end;
}

.save-btn,
.cancel-btn {
    padding: 8px 24px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.save-btn {
    background-color: #1890ff;
    color: white;
    border: none;
}

.save-btn:disabled {
    background-color: #8fc9ff;
    cursor: not-allowed;
}

.cancel-btn {
    background-color: #fff;
    border: 1px solid #ddd;
    color: #666;
}

.error-message {
    color: #ff4d4f;
    margin-bottom: 16px;
}
</style>
